<template>
  <div class="app-sidebar">
    <div class="logo-container">
      <div class="logo-content" v-if="!appStore.sidebarCollapsed">
        <img src="@/assets/logo.svg" alt="Logo" class="logo" />
        <span class="logo-text">微前端平台</span>
      </div>
      <img src="../assets/logo.svg" alt="Logo" class="logo-mini" v-else />
    </div>
    
    <el-scrollbar class="sidebar-scrollbar">
      <el-menu
        :default-active="activeMenu"
        :collapse="appStore.sidebarCollapsed"
        :unique-opened="true"
        class="sidebar-menu"
        :collapse-transition="false"
        router
      >
        <!-- 基础菜单项 -->
        <el-menu-item 
          v-for="item in basicMenuItems" 
          :key="item.path" 
          :index="item.path"
          v-show="hasRoutePermission(item)"
        >
          <el-icon><component :is="resolveDynamicComponent(getIconByName(item.icon))" /></el-icon>
          <template #title>
            <span class="menu-title">{{ item.title }}</span>
          </template>
        </el-menu-item>
        
        <!-- 应用管理菜单 -->
        <el-sub-menu index="/apps">
          <template #title>
            <el-icon><component :is="resolveDynamicComponent(Icons.Menu)" /></el-icon>
            <span class="menu-title">应用管理</span>
          </template>
          <el-menu-item
            v-for="app in allApps"
            :key="app.path"
            :index="app.path"
            v-show="hasRoutePermission(app)"
            class="submenu-item"
          >
            <el-icon>
              <component :is="resolveDynamicComponent(getIconByName(app.icon))" />
            </el-icon>
            <template #title>
              <span class="menu-title">{{ app.title }}</span>
            </template>
          </el-menu-item>
        </el-sub-menu>
        
        <!-- 动态菜单 - 从权限树生成 -->
        <template v-for="menu in dynamicMenus" :key="menu.id">
          <!-- 一级菜单 -->
          <el-sub-menu 
            v-if="menu.children && menu.children.length > 0" 
            :index="menu.path || `/menu-${menu.id}`"
          >
            <template #title>
              <el-icon><component :is="resolveDynamicComponent(getIconComponent(menu.icon))" /></el-icon>
              <span class="menu-title">{{ menu.name }}</span>
            </template>
            
            <!-- 二级菜单 -->
            <template v-for="subMenu in menu.children.filter((item: any) => item.type === 'MENU' && item.show !== false).sort((a: any, b: any) => (a.order ?? 0) - (b.order ?? 0))" :key="subMenu.id">
              <el-menu-item 
                v-if="!subMenu.children || subMenu.children.length === 0"
                :index="subMenu.path"
              >
                <el-icon><component :is="resolveDynamicComponent(getIconComponent(subMenu.icon))" /></el-icon>
                <template #title>
                  <span class="menu-title">{{ subMenu.name }}</span>
                </template>
              </el-menu-item>
              
              <!-- 三级菜单 -->
              <el-sub-menu 
                v-else 
                :index="subMenu.path || `/submenu-${subMenu.id}`"
              >
                <template #title>
                  <el-icon><component :is="resolveDynamicComponent(getIconComponent(subMenu.icon))" /></el-icon>
                  <span class="menu-title">{{ subMenu.name }}</span>
                </template>
                
                <el-menu-item 
                  v-for="childMenu in subMenu.children.filter((item: any) => item.type === 'MENU' && item.show !== false).sort((a: any, b: any) => (a.order ?? 0) - (b.order ?? 0))" 
                  :key="childMenu.id"
                  :index="childMenu.path"
                >
                  <el-icon><component :is="resolveDynamicComponent(getIconComponent(childMenu.icon))" /></el-icon>
                  <template #title>
                    <span class="menu-title">{{ childMenu.name }}</span>
                  </template>
                </el-menu-item>
              </el-sub-menu>
            </template>
          </el-sub-menu>
          
          <!-- 没有子菜单的一级菜单 -->
          <el-menu-item 
            v-else 
            :index="menu.path"
          >
            <el-icon><component :is="resolveDynamicComponent(getIconComponent(menu.icon))" /></el-icon>
            <template #title>
              <span class="menu-title">{{ menu.name }}</span>
            </template>
          </el-menu-item>
        </template>
      </el-menu>
    </el-scrollbar>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watchEffect, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAppStore } from '../store/app'
import * as Icons from '@element-plus/icons-vue'
import { resolveDynamicComponent } from 'vue'
import { microApps } from '../microApps.config'
import { usePermissionStore } from '../store/permission'
import permissionHelper from '../utils/permissionHelper'
import { useUserStore } from '../store/user'
import { ROLE_CODES } from '../store/role'
import { useUserProfile } from '../composables/useUserProfile'

const route = useRoute()
const router = useRouter()
const appStore = useAppStore()
const permissionStore = usePermissionStore()
const userStore = useUserStore()
const { fetchUserProfile } = useUserProfile()

// 当前活跃菜单
const activeMenu = computed(() => {
  // 优先匹配微应用activeRule
  const microApp = microApps.find(app => route.path.startsWith(app.activeRule))
  if (microApp) return microApp.activeRule
  // 其它业务路由
  return route.path
})

// 用户角色
const userRoles = computed(() => userStore.getUserInfo.roles || [])

// 是否超级管理员
const isSuperAdmin = computed(() => userRoles.value.includes(ROLE_CODES.SUPER_ADMIN))

// 统一的路由权限检查函数
const hasRoutePermission = (routeItem: any) => {
  // 超级管理员有所有权限
  if (isSuperAdmin.value) return true
  
  // 检查角色权限 - 扁平化处理
  const requiredRoles = routeItem.requiredRoles || []
  const hasRole = !requiredRoles.length || requiredRoles.some((role: string) => userRoles.value.includes(role))
  if (!hasRole) return false
  
  // 检查权限码 - 扁平化处理
  const permission = routeItem.permission
  if (permission && !permissionStore.hasPermission(permission)) return false
  
  return true
}

// 根据名称获取图标组件
const getIconByName = (iconName: string) => {
  if (!iconName) return Icons.Document
  return (Icons as any)[iconName] || Icons.Document
}

// 基础菜单项
const basicMenuItems = [
  { path: '/', title: '首页', icon: 'HomeFilled' },
  { path: '/dashboard', title: '仪表板', icon: 'DataBoard', requiredRoles: ['ADMIN', 'USER'] },
  { path: '/about', title: '关于系统', icon: 'InfoFilled' }
]

// 所有应用
const allApps = computed(() => {
  return microApps
    .filter(app => app.sidebar)
    .map(app => ({
      path: app.activeRule,
      title: app.title,
      icon: app.icon,
      requiredRoles: app.requiredRoles,
      permission: app.permission
    }))
})

// 检查是否有任何应用有权限显示
const hasAnyAppPermission = computed(() => {
  if (isSuperAdmin.value) return true
  return allApps.value.some(app => hasRoutePermission(app))
})

// 获取动态菜单
const dynamicMenus = computed(() => {
  const menuTree = permissionStore.getMenuTree
  // 只显示类型为MENU且show不为false的菜单项，并按order排序
  return menuTree
    .filter(menu => menu.type === 'MENU' && menu.show !== false)
    .sort((a, b) => {
      // order为0或undefined的排在前面，然后按order升序排列
      const orderA = a.order ?? 0
      const orderB = b.order ?? 0
      return orderA - orderB
    })
})

// 处理图标组件
const getIconComponent = (iconName: string) => {
  if (!iconName) return Icons.Document
  
  // 处理i-开头的图标
  if (iconName.startsWith('i-')) {
    // 移除i-前缀，转换为驼峰命名
    const iconKey = iconName
      .substring(2)
      .split('-')
      .map((part, index) => index === 0 ? part : part.charAt(0).toUpperCase() + part.slice(1))
      .join('')
    
    // 查找匹配的图标
    return (Icons as any)[iconKey] || Icons.Document
  }
  
  return (Icons as any)[iconName] || Icons.Document
}

// 确保权限数据已加载
onMounted(async () => {
  // 如果用户已登录但权限数据为空，尝试加载权限数据
  if (userStore.isLoggedIn && (!permissionStore.menuTree.length || !permissionStore.permissions.length)) {
    try {
      await fetchUserProfile()
    } catch (error) {
      console.error('[AppSidebar] 权限数据加载失败:', error)
    }
  }
})

// 监听权限数据变化，确保侧边栏能及时更新
watchEffect(() => {
  // 权限数据变化时自动更新侧边栏
  if (userStore.isLoggedIn && permissionStore.menuTree.length > 0) {
    // 侧边栏会自动响应菜单树变化
  }
})
</script>

<style scoped>
.app-sidebar {
  height: 100%;
  display: flex;
  flex-direction: column;
  color: white;
  position: relative;
  overflow: hidden;
  justify-content: flex-start;
}

.logo-container {
  height: 64px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.15);
  padding: 0 16px;
  overflow: hidden;
}

.logo-content {
  display: flex;
  align-items: center;
  width: 100%;
}

.logo {
  height: 32px;
  width: auto;
}

.logo-mini {
  height: 32px;
  width: 32px;
}

.logo-text {
  font-size: 18px;
  font-weight: 600;
  margin-left: 10px;
  letter-spacing: 1px;
  color: white;
  white-space: nowrap;
}

.sidebar-scrollbar {
  flex: none;
  border-right: none;
  max-height: calc(100vh - 114px);
}

.sidebar-menu {
  border-right: none;
  background: transparent !important;
  padding-top: 12px;
}

.sidebar-menu:not(.el-menu--collapse) {
  width: 220px;
}

/* 覆盖Element Plus默认样式 */
:deep(.el-menu) {
  background-color: transparent !important;
  border-right: none;
}
:deep(.el-menu--collapse .el-menu-tooltip__trigger){
  padding: 0 !important;
  justify-content: center;
}
:deep(.el-menu--collapse .menu-title){
  display: none !important;
}
:deep(.el-menu-item), :deep(.el-sub-menu__title) {
  display: flex !important;
  align-items: center !important;
  gap: 12px;
  padding-left: 20px !important;
  padding-right: 12px !important;
  height: 48px;
  line-height: 48px;
  color: rgba(255, 255, 255, 0.85) !important;
  background-color: transparent !important;
  border-radius: 8px;
  margin: 2px 6px;
  width: calc(100% - 12px);
  font-size: 15px;
  font-weight: 500;
  transition: all var(--transition-normal);
}

:deep(.el-menu--collapse .el-menu-item), :deep(.el-menu--collapse .el-sub-menu__title) {
  justify-content: center !important;
  padding-left: 0 !important;
  padding-right: 0 !important;
}

.menu-title {
  flex: 1;
  display: flex;
  align-items: center;
  height: 100%;
  font-size: 15px;
  font-weight: 500;
  color: inherit;
  margin-left: 0;
}

:deep(.el-icon) {
  font-size: 20px;
  min-width: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.el-menu-item.is-active) {
  color: white !important;
  background: rgba(255, 255, 255, 0.15) !important;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  font-weight: 600;
}

:deep(.el-menu-item:hover) {
  color: white !important;
  background-color: rgba(255, 255, 255, 0.1) !important;
}

:deep(.el-sub-menu__title:hover) {
  color: white !important;
  background-color: rgba(255, 255, 255, 0.1) !important;
}
:deep(.el-sub-menu__title .el-icon.el-sub-menu__icon-arrow) {
  width: auto;
}
:deep(.el-sub-menu.is-active .el-sub-menu__title) {
  color: white !important;
}

:deep(.el-menu--collapse) {
  width: 64px;
}

:deep(.el-sub-menu .el-menu-item) {
  margin: 6px 0px;
  background-color: rgba(0, 0, 0, 0.15) !important;
  margin-left: 20px !important;
  width: calc(100% - 40px) !important;
}

:deep(.el-sub-menu .el-menu-item:hover) {
  background-color: rgba(255, 255, 255, 0.1) !important;
}

:deep(.el-sub-menu .el-menu-item.is-active) {
  background-color: rgba(255, 255, 255, 0.15) !important;
}

:deep(.el-sub-menu__icon-arrow) {
  margin-left: auto !important;
  margin-right: 0 !important;
  font-size: 12px !important;
  transition: transform var(--transition-normal);
}

:deep(.el-sub-menu.is-opened .el-sub-menu__icon-arrow) {
  transform: rotate(180deg);
}

:deep(.el-menu--collapse .el-sub-menu__icon-arrow) {
  display: none !important;
}
</style> 